import pymunk
import random
from math import pi
import sys
from pymunk.pygame_util import DrawOptions
import pygame

space = pymunk.Space()
space.gravity = (0, 1000)

objects_list = []

# ball
ball_body = pymunk.Body()
ball_body.position = (250, 295)
ball_shape = pymunk.shapes.Circle(ball_body, 10)
ball_shape.mass = 10
objects_list.append((ball_body, ball_shape))

# platform
platform_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
platform_body.position = (250, 300)
platform_body.angle = random.random() * pi / 3 - pi / 6
platform_shape = pymunk.shapes.Segment(platform_body, (-40, 0), (40, 0), 3)
objects_list.append((platform_body, platform_shape))

# Add objects to space
for body, shape in objects_list:
    space.add(body, shape)


def rotate_left():
    platform_body.angle -= 0.05

def rotate_right():
    platform_body.angle += 0.05

def random_degree():
    return random.random() * pi / 3 - pi / 6

def check_game():
    x, y = ball_body.position
    if x < 0 or x > 500 or y < 0 or y > 500:
        ball_body.position = (250, 295)
        ball_body.velocity = (0, 0)
        platform_body.angle = random_degree()

def run(space: pymunk.Space):
    screen = pygame.display.set_mode((500, 500))
    option = DrawOptions(screen)
    clock = pygame.time.Clock()
    move_type = 0
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    move_type = -1
                elif event.key == pygame.K_d:
                    move_type = 1
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_a or event.key == pygame.K_d:
                    move_type = 0
        if move_type == 1:
            rotate_right()
        elif move_type == -1:
            rotate_left()
        screen.fill((255, 255, 255))
        space.step(1 / 60)
        check_game()
        space.debug_draw(option)
        pygame.display.flip()
        clock.tick(60)





if __name__ == "__main__":
    run(space)
